
import Cocoa

import ZIPFoundation
import xUtils
import xViews

import ZipArchive


public class ViewController: NSViewController {
    /// 输入框
    @IBOutlet weak var m_textField: NSSearchField!
    private var imgNames = [String]()
    
    @IBOutlet private weak var m_tableView: NSTableView!
    lazy var m_xcassetsFolderPaths = [String]()
    
    @IBOutlet weak var m_listBox: NSComboBox!
    public override func viewDidLoad() {
        super.viewDidLoad()
        title = "图片zip重命名"
        
        // 回显历史的重命名
        imgNames.append(contentsOf: xUtils.getStrsFromUserDefaults(key: "zip_img_names"))
        m_tableView.reloadData()
        
        // 给table的cell添加右键菜单
        let menu = NSMenu()
        menu.delegate = self
        m_tableView.menu = menu
        
        m_listBox.dataSource = self
        m_listBox.delegate  = self
        m_xcassetsFolderPaths.append(contentsOf: xUtils.getStrsFromUserDefaults(key: "spFolderPath"))
        m_listBox.reloadData()
        if !m_xcassetsFolderPaths.isEmpty {
            m_listBox.selectItem(at: 0)
        }
        
        // 不要搜索图标
        (m_textField.cell as? NSSearchFieldCell)?.searchButtonCell = nil
    }
    
    
    func unZipAtURL(_ zipFileURL: URL){
        
        /// 指定了路径
        if  m_listBox.stringValue.contains(".xcassets") {
            // 直接解压到文件夹xcassets，同时生成Contents.json
            
            
            // 实例化ZipArchive对象
            let archive = ZipArchive()
            // 打开zip文件
            guard archive.unzipOpenFile(zipFileURL.relativePath) else {
                xUtils.showAlter(msg: "打开zip文件失败")
                // 关闭zip文件
                archive.unzipCloseFile()
                return
            }
            
            // 获取zip文件中的文件列表
            if let contents = archive.getZipFileContents() {
                let fileCount = contents.count
                
                if fileCount == 1 {
                    xUtils.showAlter(msg: "怎么只有 1 张图片")
                    // 关闭zip文件
                    archive.unzipCloseFile()
                    return
                }
                if fileCount > 3 {
                    xUtils.showAlter(msg: "图片多于3张")
                    // 关闭zip文件
                    archive.unzipCloseFile()
                    return
                }
            }
            // 关闭zip文件
            archive.unzipCloseFile()
            
            
            
           
            
            
            zipToXcassetsFolder(zipFileURL)
        } else {
            chooseFolder(NSButton())
        }
    }
    
    func zipToXcassetsFolder (_ zipFileURL: URL) {
        let fm = FileManager.default
        let unzipFolderPath =  m_listBox.stringValue
        let imgNewName = m_textField.stringValue
        if imgNewName.isEmpty {
            xUtils.showAlter(msg: "需要重新命名")
            return
        }
        // 文件夹下有没有同名 的 te.imageset
        let findFolderPath = "\(unzipFolderPath)/\(imgNewName).imageset"
        if xUtils.isFolderExists(findFolderPath) {
            // xUtils.showAlter(msg: "有同名了，换个名字吧")
            let folderURL = URL(fileURLWithPath: findFolderPath)
            NSWorkspace.shared.open(folderURL)
            return
        }
        xUtils.createFolder(findFolderPath)
        let findFolderURL = URL(fileURLWithPath: findFolderPath)
        do {
            try fm.unzipItem(at: zipFileURL, to: findFolderURL)
            
            let secStr = "@2x.png"
            let thrStr = "@3x.png"
            guard var fileNames = fm.enumerator(atPath: findFolderURL.path)?.allObjects as? [String],
                  !fileNames.isEmpty else {
                return
            }
            fileNames.forEach { fileName in
                let zipedFilePath = "\(findFolderPath)/\(fileName)"
                if zipedFilePath.hasSuffix(secStr) || zipedFilePath.hasSuffix(thrStr) {
                    // 是2x或者3x
                } else {
                    // 不要1倍图
                    do {
                        try FileManager.default.removeItem(at: URL(fileURLWithPath: zipedFilePath))
                        print("成功：删除1x图：\(zipedFilePath)")
                    } catch {
                        print("失败：删除1x图\(error.localizedDescription)")
                    }
                }
            }
            
            fileNames = fileNames.filter({$0.hasSuffix(secStr) || $0.hasSuffix(thrStr)})
            if fileNames.isEmpty {
                xUtils.showAlter(msg: "没有发现2x或3x图片")
                return
            } else if fileNames.count == 1 {
                xUtils.showAlter(msg: "怎么只有 1 张图片")
                return
            } else  if fileNames.count == 2 {
                // 正常情况下是两张图片 2x 跟 3x
            } else  if fileNames.count == 3 {
                xUtils.showAlter(msg: "怎么有 3 张图片")
                return
            }
            
            
            // xcode 配置json
            var ContentsJson: String?
            if let jsonFilePath = Bundle.main.path(forResource: "Contents", ofType: "json") {
                do {
                    ContentsJson = try String(contentsOfFile: jsonFilePath, encoding: .utf8)
                } catch {
                    print("读取Contents.json 遇到了错误：\(error.localizedDescription)")
                    
                }
            } else {
                print("没有找到 Contents.json 文件")
            }
            for fileName in fileNames  {
                
                if !fileName.contains(imgNewName) && (fileName.hasSuffix(secStr) || fileName.hasSuffix(thrStr)) {
                    var pngFileURL = findFolderURL
                    pngFileURL.appendPathComponent(fileName)
                    
                    let fileName = fileName.hasSuffix(secStr) ? (imgNewName+secStr) : (imgNewName+thrStr)
                    let newPngFileURL = findFolderURL.appendingPathComponent(fileName)
                    do {
                        try fm.moveItem(at: pngFileURL, to: newPngFileURL)
                        
                        
                        let newNames = xUtils.saveStrToStrArr(key: "zip_img_names" , saveStr: imgNewName )
                        if !newNames.isEmpty {
                            imgNames.removeAll()
                            imgNames.append(contentsOf: newNames)
                            m_tableView.reloadData()
                        }
                        if fileName.hasSuffix(secStr) {
                            ContentsJson = ContentsJson?.replacingOccurrences(of: "编组 5@2x.png", with: fileName)
                        }
                        else if fileName.hasSuffix(thrStr) {
                            ContentsJson = ContentsJson?.replacingOccurrences(of: "编组 5@3x.png", with: fileName)
                        }
                        
                    } catch {
                        print("移动文件遇到了错误：\(error.localizedDescription)")
                    }
                    
                    
                } else {
                    print(fileName)
                }
                
            }
            // 写入content.json
            if let json = ContentsJson, !json.isEmpty {
                do {
                    try Data(json.utf8).write(to: URL(fileURLWithPath: "\(findFolderPath)/Contents.json"), options: .atomic)
                } catch {
                    print(error)
                }
            }
            
        } catch {
            print("解压缩文件遇到了错误：\(error.localizedDescription)")
        }
        
    }
    
    @IBAction func doubleAction(_ sender: NSTableView) {
        let idx = sender.selectedRow
        if idx >= 0, idx < imgNames.count {
            m_textField.stringValue = imgNames[idx]
        }
        
    }
    // 指定文件病例
    @IBAction func chooseFolder(_ sender: NSButton) {
        
        xUtils.chooseFolder(for: view.window) { folderPath in
            if folderPath.contains(".xcassets") {
                let folderPaths = xUtils.saveStrToStrArr(key: "spFolderPath", saveStr: folderPath)
                
                if !folderPaths.isEmpty {
                    self.m_xcassetsFolderPaths.removeAll()
                    self.m_xcassetsFolderPaths.append(contentsOf: folderPaths)
                    self.m_listBox.reloadData()
                    if let desIdx = self.m_xcassetsFolderPaths.firstIndex(of: folderPath) {
                        self.m_listBox.selectItem(at: desIdx)
                    }
                }
            }
        }
    }
    
}
extension ViewController: FileDragDelegate {
    public func didFinishDrag(_ URLs: [URL]) {
        
        let fileURL = URLs[0]
        let ext = fileURL.pathExtension
        switch ext {
        case "zip":
            debugPrint("收到zip文件：\(fileURL)")
            unZipAtURL(fileURL)
        default:
            print(ext)
        }
    }
}
// MARK: - NSTableViewDataSource
extension ViewController: NSTableViewDataSource {
    public func numberOfRows(in tableView: NSTableView) -> Int {
        return imgNames.count
    }
}
// MARK: - NSTableViewDelegate
extension ViewController: NSTableViewDelegate {
    public func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        
        let imgName = imgNames[row]
        if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier("his"), owner: self) as? NSTableCellView {
            cell.textField?.stringValue = imgName
            return cell
        }
        return nil
    }
}
// MARK: - NSMenuDelegate
extension ViewController: NSMenuDelegate {
    public func menuNeedsUpdate(_ menu: NSMenu) {
        menu.removeAllItems()
        // 在这里动态添加 menu item
        menu.addItem(NSMenuItem(title: "删除引用", action: #selector(handleDeleteClickedRow), keyEquivalent: ""))
    }
    @objc func handleDeleteClickedRow(){
        let idx = m_tableView.selectedRow
        guard idx >= 0,
              m_tableView.clickedColumn >= 0,
              let row: NSTableRowView = m_tableView.rowView(atRow: idx, makeIfNecessary: false),
              let cellView = row.view(atColumn: m_tableView.clickedColumn) as? NSTableCellView  else {
            return
        }
        
        //                刷新
        imgNames.remove(at: idx)
        m_tableView.reloadData()
        //                偏好同步
        UserDefaults.standard.set(imgNames, forKey: "zip_img_names")
        
    }
}
extension ViewController: NSComboBoxDataSource {
    public func comboBox(_ aComboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
        guard index < m_xcassetsFolderPaths.count else {
            return nil
        }
        return m_xcassetsFolderPaths[index]
    }
    
    public func numberOfItems(in aComboBox: NSComboBox) -> Int {
        return m_xcassetsFolderPaths.count
    }
}
extension ViewController: NSComboBoxDelegate {
    public func comboBoxSelectionDidChange(_ notification: Notification) {
        if let comboBox = notification.object as? NSComboBox, comboBox === m_listBox {
            guard comboBox.indexOfSelectedItem < m_xcassetsFolderPaths.count else { return }
            
        }
    }
}


